package com.dbpms.pj.sys.service.realm;


import com.dbpms.pj.sys.dao.SysMenuDao;
import com.dbpms.pj.sys.dao.SysRoleMenuDao;
import com.dbpms.pj.sys.dao.SysUserDao;
import com.dbpms.pj.sys.dao.SysUserRoleDao;
import com.dbpms.pj.sys.pojo.SysUser;
import org.apache.shiro.authc.*;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @Author: Song Yu
 * @Date: 2020/10/26 16:41
 */

@Component
public class ShiroUserRealm extends AuthorizingRealm {

    @Autowired
    SysUserDao sysUserDao;

    @Autowired
    SysMenuDao sysMenuDao;

    @Autowired
    SysRoleMenuDao sysRoleMenuDao;

    @Autowired
    SysUserRoleDao sysUserRoleDao;

    /** 获取并封装授权信息(做授权业务时写此方法) */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection authenticationToken)throws AuthorizationException{
        //1.获取用户信息
        SysUser sysUser = (SysUser) authenticationToken.getPrimaryPrincipal();
        //2.根据userId查询roleIds
        Integer[] roleIds = sysUserRoleDao.findRoleIdsByUserId(sysUser.getId());
        if(roleIds==null||roleIds.length==0)
            throw new AuthorizationException();
        //3.根据roleIds查询menuIds
        List<Integer>menuIds = sysRoleMenuDao.findMenuIdsByRoleIds(roleIds);
        if(menuIds==null||menuIds.size()==0)
            throw new AuthorizationException();
        //4.基于菜单id获取权限标识(sys_menus)
        List<String> permissions=
                sysMenuDao.findPermissions(menuIds);
        //5.对权限标识信息进行封装并返回
        Set<String> set=new HashSet<>();
        for(String per:permissions){
            if(!StringUtils.isEmpty(per)){
                set.add(per);
            }
        }
        SimpleAuthorizationInfo info=
                new SimpleAuthorizationInfo();
        info.setStringPermissions(set);
        return info;//返回给授权管理器
    }

    /** 获取并封装认证信息 */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //1.获取登陆时输入的登录名
        UsernamePasswordToken uToken = (UsernamePasswordToken)authenticationToken;
        String username = uToken.getUsername();
        //2.基于用户名查询数据库中的用户信息
        SysUser user = sysUserDao.findUserByUsername(username);
        //3.校验用户是否存在
        if(user==null)throw new UnknownAccountException();
        //4.校验用户是否已被禁用
        if(user.getValid()==0)throw new LockedAccountException();
        //5.封装认证信息实现密码认证（底层）
        ByteSource creddentialsalt = ByteSource.Util.bytes(user.getSalt());
        return new SimpleAuthenticationInfo(user,user.getPassword(),creddentialsalt,getName());
    }

    /** 置凭证匹配器(与用户添加操作使用相同的加密算法)，
     * 此方法返回凭证加密对象，基于此对象对用户输入的密码进行加密操作
     */
    @Override
    public CredentialsMatcher getCredentialsMatcher() {
        HashedCredentialsMatcher credentialsMatcher = new HashedCredentialsMatcher();
        credentialsMatcher.setHashAlgorithmName("MD5");
        credentialsMatcher.setHashIterations(1);
        return credentialsMatcher;
    }//对于此get方法而言，也可以重写set方法
}
